import { NextFunction, Request, Response } from 'express'
import UserAuthError from '@/errors/UserAuthError'
import UserTokenService from '@/models/mongo/UserTokenService'
import { getUserToken } from '@/utils'

// 用户认证中间件
export default async (req: Request, res: Response, next: NextFunction) => {
  try {
    const token = getUserToken(req)
    if (!token) {
      throw new UserAuthError('请登录后再操作')
    }
    await UserTokenService.validateToken(req, res, next)
  } catch (error) {
    // 异常则执行
    next(error)
  }
}
